package com.pandy.code;

import javax.swing.tree.TreeNode;
import java.util.List;

/**
 * @description: 二叉树遍历
 * @author: panhong
 * @date: 2025/3/28
 */
public class Code11_BinaryTree_Traverse {

    /**
     * 前序：先头节点，再左子树，最后右子树
     * @param root
     */
    public static void preorder(BinaryNode root) {
        if(root != null) {
            System.out.print(root.value + "  ");
            preorder(root.left);
            preorder(root.right);
        }
    }

    /**
     * 中序：先左子树，再头节点，最后右子树
     * @param root
     */
    public static void order(BinaryNode root) {
        if(root != null) {
            order(root.left);
            System.out.print(root.value + "  ");
            order(root.right);
        }
    }

    /**
     * 后序：先左子树，再右子树，最后头节点
     * @param root
     */
    public static void postorder(BinaryNode root) {
        if(root != null) {
            postorder(root.left);
            postorder(root.right);
            System.out.print(root.value + "  ");
        }
    }

    public static void main(String[] args) {
        BinaryNode n1 = new BinaryNode(1);
        BinaryNode n2 = new BinaryNode(2);
        BinaryNode n3 = new BinaryNode(3);
        BinaryNode n4 = new BinaryNode(4);
        BinaryNode n5 = new BinaryNode(5);
        BinaryNode n6 = new BinaryNode(6);
        BinaryNode n7 = new BinaryNode(7);
        BinaryNode n8 = new BinaryNode(8);

        n1.left = n2;
        n1.right = n3;
        n2.left = n4;
        n2.right = n5;
        n4.left = n8;
        n3.left = n6;
        n3.right = n7;

        System.out.println("=========前序遍历二叉树=========");
        preorder(n1);

        System.out.println();
        System.out.println("=========中序遍历二叉树=========");
        order(n1);

        System.out.println();
        System.out.println("=========后序遍历二叉树=========");
        postorder(n1);
    }
}
